<?php
namespace app\admin\controller;

use app\admin\model\VideoLibrary as VideoLibraryModel;
use app\admin\model\Device as DeviceModel;
use app\admin\model\Account as AccountModel;
use app\admin\org\HttpRequest;
use think\Db;
use think\Request;


class VideoLibrary extends Base
{
    public function index()
    {
        $model = new AccountModel;

        //搜索名称
        $phname = $this->request->param("phname");

        //渲染页面模板
        $model->field('id,username')->where('password', '<>', '');
       /* $model->field('v.id,v.title,v.count,v.duration,v.upload_mode,v.if_url,v.url,v.created_at,v.updated_at,d.name,d.sn,u.username')
            ->alias('v')
            ->join('user u','v.user_id__ = u.id ','left')
            ->join('device d','v.device_id = d.id','left')
            ->order('v.id','desc');*/
        //->select();
        // ->paginate(5);

        if(!empty($phname)){
            $model->where('username','like', '%'.$phname.'%');
        }
        $result = $model->paginate(10,false,[
            'query'=>['phname'=>$phname]
        ]);

        //计算总共记录条数
        $count = $result->total();
        //分页
        $page = $result->render();

        //接收ajax传递的值
        $request = request();
        $ispost = $request->isPost();
        if($ispost){
            $id = $_POST["viewId"];
            //调用接口查询视频数据
           /* return json([
                'code' => 200,
                'view'=>$video_name,
            ]);*/
        }
        $this->assign('currentPage',$result->currentPage());
        $this->assign('lastPage',$result->lastPage());
        $this->assign('page',$page);
        //$this->assign('device',$device);
        $this->assign('user',$result);

       // $this->assign('video',$video);
        $this->assign('count',$count);
        $this->assign('empty',"暂无数据");
        return $this->fetch();
    }

    // 设备文件
    // 有 device_id，则某个具体设备的文件列表；
    // 没有 device_id，则该用户的所有设备的文件列表；
    public function fileListx($id)
    {
        try {
            // 用户名和密码
            $user = \think\Db::name('user')->field(['username', 'password', 'password2'])->where('id', $id)->whereNull('deleted_at')->find();
            // $user =["username"=>"17717914232","password"=>"123456","password2"=>"abc123456abc"];
            $user['base64_username'] = base64_encode($user['username']);

            // 用户所有设备的文件  获取最新绑定的 解绑的视频不显示 deleted_at可以显示解绑视频
            // $imeiArr = ['53810053839'];
            $imeiArr = DeviceModel::where('user_id', $id)->column('imei');

            //imei目录下面的直接文件 ts的视频文件
            $type = '';
            $files = [];
            $agent = \think\Config::get('clouddisk.agent');
            foreach ($imeiArr as $key => $imei) {
                // 从云盘中获取文件
                $res = $this->_cloudDisk($imei . $type, $user['username'], substr($user['password2'], 3, -3));
                // var_dump($res);exit;
                // 只有一个设备， 并且目录不存在，直接返回空数组；
                if ($res['code'] !== 200 && count($imeiArr) === 1) {
                    return json([
                        'code'=>200,
                        'message'=>'暂无数据',
                        'data'=>['list' => []]
                    ]);
                }

                // $key1 是文件名，比如 "/remote.php/webdav/test/HSBCnet.mp4"；
                // $value 是文件属性的数组，比如
                /* array(5) {
                    //["{DAV:}getcontentlength"]=> string(8) "40139260"
                    ["{DAV:}getcontenttype"]=> string(9) "video/mp4"
                    //["{DAV:}getetag"]=> string(34) ""7da2b6b38585f2d804f80434af34a935""
                    ["{DAV:}getlastmodified"]=> string(29) "Sun, 24 Mar 2019 09:58:30 GMT"
                    //["{DAV:}resourcetype"]=> NULL
                }
                其中，只有 "{DAV:}getcontenttype" 和 "{DAV:}getlastmodified" 有意义；
                而且，返回的数据是按文件名排序的， 并不是按创建时间倒序；
                */
                if (isset($res['data'])) {
                    foreach ($res['data'] as $key1 => $value) {
                        // 去除目录，比如当前目录本身，以及可能的 lock 目录；
                        if (isset($value['{DAV:}getcontenttype'])) {
                            $basename = basename($key1);
                            array_push($files, [
                                'userId' => $id,
                                'userdata' => $user,
                                'imei' => $imei,
                                'filename' => $basename,
                                //'url' => 'http://58.57.117.132:9801' . $key,
                                'url' => $agent . $user['base64_username'] . '/' . $user['password'] . '/' . $imei . $type . '/' . $basename,
                                'thumb_url' => ''
                            ]);
                        }
                    }
                }
            }

            return json([
                'code' => 200,
                'data'=>[
                    'list'=>$files,
                    'hasMore'=>false
                    ]
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 4000,
                'message'=>$e->getMessage()
            ]);
        }
    }

    // 封装云盘读取
    // 每个用户的行车记录仪上传的文件在该设备的imei为目录名称的目录下
    private function _cloudDisk($imei, $username, $password) {
        try {
            $url = \think\Config::get('clouddisk.domain') . 'remote.php/webdav/' . $imei;
            $settings = array(
                'baseUri' => $url,
                'userName' => $username,
                'password' => $password
            );
            $client = new \Sabre\DAV\Client($settings);

            $response = $client->propFind($url, array(
                // $response = $client->propFind('collection', array(
                // '{DAV:}getcontentlength',
                '{DAV:}displayname',
                '{DAV:}getcontenttype',
                // '{DAV:}getetag',
                // '{DAV:}getlastmodified'
            ), 1);
            // 当访问不存在的目录时，直接被catch了，下面这个ve 不会执行；
            // \Dev::ve($response);
            return ['code'=>200, 'data'=>$response];
        } catch (\Exception $e) {
            return [
                'code' => 4000,
                'message'=>$e->getMessage()
                ];
        }
    }

    //删除单条记录
    public function delete($id)
    {
        $result = VideoLibraryModel::update(['deleted_at'=>date('Y-m-d H:i:s')],['id'=>$id]);//软删除

        if($result){
            return json([
                'code' => 200,
            ]);
        }

    }

    //批量删除
    public function deleteArr()
    {
        $ispost = $this->request->isPost();
        if ($ispost) {
            $idArr = $this->request->post();

            $result = VideoLibraryModel::where('id','exp','in('.implode(',',$idArr['id']).')')->update(['deleted_at'=>date('Y-m-d H:i:s')]);//软删除

            if($result){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }

    //下载
    public function download($url)
    {
        $file_dir = ROOT_PATH . 'public'  . $url;    // 下载文件存放目录
        // 检查文件是否存在
        if (! file_exists($file_dir) ) {
            $this->error('文件未找到');
        }else {
            try{
                // 打开文件
                $file1 = fopen($file_dir, "r");
                $fileSize = filesize($file_dir);
                // 输入文件标签
                Header("Content-type: application/octet-stream");
                Header("Accept-Ranges: bytes");
                Header("Accept-Length:" . $fileSize);
                Header("Content-Disposition: attachment;filename=" . basename($file_dir));
                ob_clean();     // 重点！！！
                flush();        // 重点！！！！可以清除文件中多余的路径名以及解决乱码的问题：
                //输出文件内容
                //读取文件内容并直接输出到浏览器
                echo fread($file1, $fileSize);
                fclose($file1);
                exit();
            }catch (\Exception $e){
                return json([
                    'code' => 4000,
                    'message'=>$e->getMessage()
                ]);
            }
        }
    }

    //播放
    public function play($filename,$userid,$imei)
    {
        try{
            // var_dump(ROOT_PATH);exit;
            $ispost = $this->request->isPost();
            if($ispost) {
                ini_set('max_execution_time', 0);//
                $userdata = $this->request->post();

                //$model = new VideoLibraryModel;
                $model = VideoLibraryModel::field('id,title,user_id,server_url')->where('user_id',$userid)->where('title',$filename)->find();

                if(!is_null($model)){
                    return json([
                        'code' => 200,
                        'url'=>$model["server_url"],
                    ]);
                }else{
                    //var_dump("http://cloud.leeker.cc:8000/remote.php/webdav/".$imei.DS.$filename);exit;
                    $content=HttpRequest::download("https://cloud.leeker.cc:1443/remote.php/webdav/".$imei.'/'.$filename,null,$userdata["userdata"]);
                    $file_dir = ROOT_PATH . 'public/static/clouddisk/'.$filename;    // 下载文件存放目录
                    $server_url = '/static/clouddisk/'.$filename;
                    file_put_contents($file_dir,$content);
                    $model = new VideoLibraryModel;

                    //php转码ts视频文件
                    $filename2 = str_replace(strrchr(basename($filename), '.'), '', basename($filename));
                    //exec('D:/ffmpeg-20190812-9fdc7f1-win64-static/bin/ffmpeg.exe  -i  '.$file_dir.' '.ROOT_PATH . 'public/static/clouddisk/'.$filename2.'.mp4');//-c:v libx264 -strict -2
                    exec('ffmpeg  -i  '.$file_dir.' '.ROOT_PATH . 'public/static/clouddisk/'.$filename2.'.mp4');//-c:v libx264 -strict -2
                    /*$path = [
                        'ffmpeg.binaries' => 'D:/ffmpeg-20190812-9fdc7f1-win64-static/bin/ffmpeg.exe',
                        'ffprobe.binaries' => 'D:/ffmpeg-20190812-9fdc7f1-win64-static/bin/ffprobe.exe',
                    ];
                    $ffmpeg = \FFMpeg\FFMpeg::create($path);
                    $video = $ffmpeg->open($file_dir);
                    $format = new \FFMpeg\Format\Video\X264('libfdk_aac');//'libfdk_aac'*/
                    //$format->setKiloBitrate(1000)->setAudioChannels(2)->setAudioKiloBitrate(256);
                    /*$format->on('progress', function ($video, $format, $percentage) {
                        echo "$percentage % 进度";
                    });*/
                    /*$filename = str_replace(strrchr(basename($filename), '.'), '', basename($filename));
                    $re = $video->save($format, ROOT_PATH . 'public/static/clouddisk/'.$filename.'.mp4');*/
                    $playurl = '/static/clouddisk/'.$filename2.'.mp4';
                    $model->save(['user_id'=>$userid,'server_url'=>$playurl,'title'=>$filename]);
                    return json([
                        'code' => 200,
                        'url'=>$playurl,
                    ]);
                }
            }
        }catch (\Exception $e){
            return json([
                'code' => 4000,
                'message'=>$e->getMessage()
            ]);
        }
    }


    //播放
    public function play2()
    {

        $filename = 'F20190809180044S.ts';
        $filename2 = str_replace(strrchr(basename($filename), '.'), '', basename($filename));
        $file_dir = ROOT_PATH . 'public/static/clouddisk/'.$filename;    // 下载文件存放目录

        ini_set('max_execution_time', 0);//

        $rrr = exec('D:/ffmpeg-20190812-9fdc7f1-win64-static/bin/ffmpeg.exe  -i  '.$file_dir.' '.ROOT_PATH . 'public/static/clouddisk/'.$filename2.'.mp4',$status);//-c:v libx264 -strict -2

        //php转码ts视频文件
        /*$path = [
            'ffmpeg.binaries' => 'D:/ffmpeg-20190812-9fdc7f1-win64-static/bin/ffmpeg.exe',
            'ffprobe.binaries' => 'D:/ffmpeg-20190812-9fdc7f1-win64-static/bin/ffprobe.exe',
        ];
        $ffmpeg = \FFMpeg\FFMpeg::create($path);
        $video = $ffmpeg->open($file_dir);
        $format = new \FFMpeg\Format\Video\X264('libfdk_aac');//'libfdk_aac'
        //$format->setKiloBitrate(1000)->setAudioChannels(2)->setAudioKiloBitrate(256);
        /*$format->on('progress', function ($video, $format, $percentage) {
            echo "$percentage % 进度";
        });

        $video->save($format, ROOT_PATH . 'public/static/clouddisk/'.$filename.'.mp4');
        */
        exit;
    }
}